<template>
  <view class="lanya">
    <view v-for="(item, index) in deviceList" style="width: 94%; margin-left: 3%; height: 250rpx; background: #293241; margin-top: 20rpx; border-radius: 0.3em">
      <view style="width: 90%; margin-left: 5%; padding-top: 10px">
        <image src="../../../static/home/ly.png" style="float: left; width: 120rpx; height: 120rpx" mode=""></image>
        <view style="float: left; margin-left: 10px">
          <view style="color: #fff; font-size: 32rpx">
            {{ item.name }}
          </view>
          <view style="font-size: 16rpx; color: #999; margin-top: 5rpx">
            UUID:
            <text v-if="is_ios == 1">
              {{ item.ios_deviceId }}
            </text>
            <text v-else>
              {{ item.deviceId }}
            </text>
          </view>
          <view style="font-size: 18rpx; color: #999; margin-top: 5rpx">
            Service
            <text v-if="lang == 0"> 数量 </text>
            <text v-else> num </text>
            ：{{ item.advertisServiceUUIDs.length }}
          </view>
        </view>
        <view>
          <view style="color: #999; width: 100%; float: left; margin-top: 10px">
            <text v-if="lang == 0"> 信号强度 </text>
            <text v-else> Signal strength </text>

            ： <span style="color: green">{{ item.RSSI }}dBm({{ 100 - Math.abs(item.RSSI) }}%)</span>

            <view
              v-if="deviceInfo && deviceInfo.deviceId == item.deviceId"
              @tap="handleCloseDevice_clone(item)"
              style="
                float: right;
                margin-right: 10px;
                border-radius: 0.3em;
                background: #df202f;
                width: 70px;
                color: #fff;
                height: 50rpx;
                line-height: 50rpx;
                text-align: center;
              "
            >
              <text v-if="lang == 0"> 断开连接 </text>
              <text v-else> Disconnect </text>
            </view>

            <view
              v-else
              @tap="handleConnectDevice(item)"
              style="
                float: right;
                margin-right: 10px;
                border-radius: 0.3em;
                background: #507afe;
                width: 70px;
                color: #fff;
                height: 50rpx;
                line-height: 50rpx;
                text-align: center;
              "
            >
              <text v-if="lang == 0"> 连接 </text>
              <text v-else> connect </text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 
    <button size="mini" type="warn" v-if="deviceInfo.deviceId" @click="handleWriteValue">向低功耗蓝牙设备特征值中写入二进制数据</button>

    <button size="mini" type="warn" v-if="deviceInfo.deviceId" @click="handleCloseDevice">断开连接</button -->
  </view>
</template>

<script>
import { setProperty } from "../../../uni_modules/uv-ui-tools/libs/function";
var app = getApp();
// import { setTimeout } from '../../../utils/mqtt'
var errorCode = {
  "-1": "已连接",
  10000: "未初始化蓝牙适配器",
  10001: "当前蓝牙适配器不可用",
  10002: "没有找到指定设备",
  10003: "连接失败",
  10004: "没有找到指定服务",
  10005: "没有找到指定特征值",
  10006: "当前连接已断开",
  10007: "当前特征值不支持此操作",
  10008: "其余所有系统上报的异常",
  10009: "系统版本低于 4.3 不支持 BLE",
  10010: "已连接",
  10011: "配对设备需要配对码",
  10012: "连接超时",
  10013: "连接 deviceId 为空或者是格式不正确",
};

export default {
  name: "bluetooth",
  data() {
    return {
      tanchu: 0,
      lian: 0,
      is_ios: 0,
      user_uuid: 0,
      nub_time_d: 0,
      nub_times: null,
      nub_time: 0,
      lang: 0,
      // 是否初始化了蓝牙模块
      isInitBluetooth: false,
      // 是否搜索中
      isSearching: false,

      // 搜索到的设备列表
      deviceList: [],

      // 当前连接的蓝牙设备信息
      deviceInfo: {},
      // 当前连接的蓝牙设备的服务信息
      serviceInfo: {},
      // 支持 write 的特征值信息
      writeCharacteristicsInfo: {},
      // 支持 notify 或者 indicate 的特征值信息
      notifyCharacteristicsInfo: {},

      // ----------
      error_show: 0,
      h_i: 0,
      h_f: 0x00,
      h_time: null,
      data: {
        pm_type_index: "",
      },
    };
  },
  onPullDownRefresh() {
    console.log("loading.....");
    uni.showLoading({ title: "loading.....", mask: false });

    this.deviceList = [];
    let that = this;

    // uni.stopBluetoothDevicesDiscovery({
    //   success(res) {
    //     console.log(res)
    //   },
    //   fail(error) {

    //   },
    // })

    setTimeout(function () {
      // uni.stopPullDownRefresh();
      uni.hideLoading();
      that.lood();
    }, 500);
  },
  onShow() {
    let platform = uni.getSystemInfoSync().platform;
    if (platform === "ios") {
      this.is_ios = 1; // 苹果
    } else {
      this.is_ios = 0;
      //   // 其他
      console.log("其他");
    }

    this.error_show = 0;
    if (uni.getStorageSync("lang")) {
      this.lang = uni.getStorageSync("lang");
    }

    if (this.lang == 1) {
      uni.setNavigationBarTitle({
        title: "Connect Bluetooth",
      });
    } else {
      uni.setNavigationBarTitle({
        title: "连接蓝牙",
      });
    }

    if (uni.getStorageSync("user_uuid")) {
      this.user_uuid = uni.getStorageSync("user_uuid");
    }

    this.lian = 0;

    if (this.lang == 1) {
      var errorCode = {
        "-1": "Connected",
        10000: "Bluetooth adapter not initialized",
        10001: "The current Bluetooth adapter is not available",
        10002: "The specified device was not found",
        10003: "connect failed",
        10004: "The specified service was not found",
        10005: "The specified feature value was not found",
        10006: "The current connection has been disconnected",
        10007: "The current feature value does not support this operation",
        10008: "All other anomalies reported by the system",
        10009: "System version below 4.3 does not support BLE",
        10010: "Connected",
        10011: "Pairing devices require a pairing code",
        10012: "connection timed out",
        10013: "The connection deviceId is empty or formatted incorrectly",
      };
    }
    console.log(errorCode, this.lang, uni.getStorageSync("lang"), 7777777777);

    this.lood();
    //handleConnectDevice
    //要去他的页面的
  },
  onLoad() {
    this.error_show = 0;

    app.globalData.cli_lan = 0;
    // uni.stopBluetoothDevicesDiscovery({
    //   success(res) {
    //     console.log("停止蓝牙",res)
    //   },
    //   fail(error) {

    //   },
    // })
    // if(this.nub_times){
    // 	clearInterval(this.nub_times)
    // 	this.nub_time = 0;
    // }
  },
  onHide() {
    this.nub_time_d = 1;
    console.log(22222);
    // uni.stopBluetoothDevicesDiscovery({
    //   success(res) {
    //     console.log(res)
    //   },
    //   fail(error) {

    //   },
    // }).
    // if(this.nub_times){
    // 	clearInterval(this.nub_times)
    // 	this.nub_time = 0;
    // }
  },
  onUnload() {
    this.nub_time_d = 1;
    console.log(111111234561);
    let that = this;

    // uni.setStorageSync('lan_bug',0);

    uni.setStorageSync("dev_data", that.data);
    uni.setStorageSync("deviceList", that.deviceList);
    uni.setStorageSync("serviceInfo", that.serviceInfo);

    if (that.writeCharacteristicsInfo != {}) {
      uni.setStorageSync("writeCharacteristicsInfo", that.writeCharacteristicsInfo);
    }

    if (that.notifyCharacteristicsInfo != {}) {
      uni.setStorageSync("notifyCharacteristicsInfo", that.notifyCharacteristicsInfo);
    }

    //notifyCharacteristicsInfo

    /**/
    uni.setStorageSync("deviceInfo", that.deviceInfo);
    //传 数据

    this.handleStopSearch();
  },

  methods: {
    data_che() {
      let that = this;

      setTimeout(function () {
        console.log("读秒结束", that.nub_time_d);
        if (that.nub_time_d == 0) {
          app.globalData.connected = true;
          app.globalData.is_rw = 0;
          app.globalData.is_yuancheng = 0;
          app.globalData.error_code = 0;

          //当前状态
          console.log("app.globalData.connected", app.globalData.connected);

          // uni.setStorageSync('lan_bug',0);

          uni.setStorageSync("dev_data", that.data);
          uni.setStorageSync("deviceList", that.deviceList);
          uni.setStorageSync("serviceInfo", that.serviceInfo);

          uni.setStorageSync("writeCharacteristicsInfo", that.writeCharacteristicsInfo);
          //notifyCharacteristicsInfo
          uni.setStorageSync("notifyCharacteristicsInfo", that.notifyCharacteristicsInfo);
          /**/
          uni.setStorageSync("deviceInfo", that.deviceInfo);

          uni.hideLoading();

          if (that.lang == 1) {
            if (that.tanchu == 0) {
              that.tanchu = 1;
              uni.showModal({
                title: "Failed to read controller parameters",
                // content: '您的位置信息将用获取信息',
                success: (res) => {
                  uni.navigateBack({
                    //返回上一个页面
                    delta: 1,
                  });
                },
              });
              setTimeout(function () {
                that.tanchu = 0;
              }, 5000);
            }
          } else {
            if (that.tanchu == 0) {
              that.tanchu = 1;
              uni.showModal({
                title: "读取控制器参数失败",
                // content: '您的位置信息将用获取信息',
                success: (res) => {
                  // uni.navigateBack({//返回上一个页面
                  // delta: 1
                  // });
                },
              });
              setTimeout(function () {
                that.tanchu = 0;
              }, 5000);
            }
          }
        }
      }, 10000);

      // this.nub_times = setInterval(function () {
      //   that.nub_time++;
      //   console.log("检测时间...",that.nub_time)
      //   if(that.nub_time >= 10){
      // 	  clearInterval(that.nub_times)

      // 			if(this.nub_time_d == 0){
      // 				uni.showModal({
      // 					title: 'Failed to read controller parameters',
      // 					// content: '您的位置信息将用获取信息',
      // 					success: (res) => {
      // 						uni.navigateBack({//返回上一个页面
      // 								delta: 1
      // 						});
      // 					}
      // 				})
      // 			}else{

      // 				uni.showModal({
      // 					title: '读取控制器参数失败',
      // 					// content: '您的位置信息将用获取信息',
      // 					success: (res) => {
      // 						  uni.navigateBack({//返回上一个页面
      // 								delta: 1
      // 						  });
      // 					}
      // 				})
      // 			}
      //   }
      // }, 1000)
    },
    lood() {
      if (app.globalData.connected == true) {
        //已连接设置 直接加入
        this.deviceList = uni.getStorageSync("deviceList");
        this.deviceInfo = uni.getStorageSync("deviceInfo");
        this.data = uni.getStorageSync("dev_data");
        this.serviceInfo = uni.getStorageSync("serviceInfo");
        this.notifyCharacteristicsInfo = uni.getStorageSync("notifyCharacteristicsInfo");
        this.writeCharacteristicsInfo = uni.getStorageSync("writeCharacteristicsInfo");
      } else {
        if (this.lang == 1) {
          uni.showLoading({ title: "searcging...", mask: false });
        } else {
          uni.showLoading({ title: "正在搜索设备", mask: false });
        }

        // 初始化蓝牙模块
        this.handleInitBluetooth();
        this.handleCloseDevice = "";
      }

      let that = this;

      // 监听蓝牙适配器状态变化事件
      uni.onBluetoothAdapterStateChange((result) => {
        console.log("蓝牙适配器状态改变", result);
        // 蓝牙适配器是否可用
        if (result.available) {
          console.log("蓝牙可用,888888888");
        } else {
          //如果蓝牙断开
          console.log("蓝牙不可用,99999999999");
          uni.stopBluetoothDevicesDiscovery({
            success(res) {},
            fail(error) {},
          });

          if (that.lang == 1) {
            uni.setStorageSync("deviceList", null);
            uni.setStorageSync("deviceInfo", null);
            app.globalData.connected = false;

            uni.showLoading({ title: "Bluetooth disconnected/turned off", mask: false });
          } else {
            uni.setStorageSync("deviceList", null);
            uni.setStorageSync("deviceInfo", null);
            app.globalData.connected = false;
            if (that.lang == 0) {
              uni.showToast({ title: "蓝牙已断开/关闭", icon: "none" });
            } else {
              uni.showLoading({ title: "Bluetooth disconnected/turned off", icon: "none" });
            }
            // uni.showToast({ title: '蓝牙已断开/关闭', icon: 'none' })
          }

          // 停止搜索
        }
        // 蓝牙适配器是否处于搜索状态
        if (result.discovering) {
          console.log("正在搜索");
        } else {
          console.log("搜索已停止");
        }
        this.isSearching = result.discovering;
      });

      uni.getBluetoothAdapterState({
        success: function (res) {
          console.log("蓝牙状态：", res);
        },
        fail: function (res) {
          console.log("获取蓝牙状态失败");
        },
      });

      // 监听寻找到新设备的事件
      uni.onBluetoothDeviceFound((result) => {
        uni.hideLoading();

        const deviceInfo = result.devices[0];
        if (deviceInfo.name) {
          const deviceIndex = that.deviceList.findIndex((item) => item.deviceId === deviceInfo.deviceId);

          let ios_deviceId = 0;
          if (that.is_ios == 1) {
            function ab2hex(buffer) {
              const hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
                return ("00" + bit.toString(16)).slice(-2).toUpperCase();
              });
              return hexArr.join(":").slice(6);
            }

            deviceInfo.ios_deviceId = ab2hex(deviceInfo.advertisData);
          } else {
            deviceInfo.ios_deviceId = 0;
          }

          if (deviceIndex >= 0) {
            that.deviceList[deviceIndex] = deviceInfo;
            let data_arr = that.deviceList;

            that.deviceList = [];
            that.deviceList = data_arr;
          } else {
            that.deviceList.push(deviceInfo);
          }
        }
      });

      // ArrayBuffer转16进度字符串示例
      function ab2hex(buffer) {
        const hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
          return ("00" + bit.toString(16)).slice(-2);
        });
        return hexArr.join("");
      }

      //写个检测的
      console.log("设置监听");

      // 监听低功耗蓝牙设备的特征值变化事件。必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
      uni.onBLECharacteristicValueChange((res) => {
        const value = Array.prototype.map.call(new Uint8Array(res.value), (bit) => bit);

        // heartbeat/
        console.log("9797监听到的值", value.length, value);

        if (value.toString() == [170, 12, 0, 16, 1, 31, 0, 0, 0, 0, 0, 0, 219, 121].toString()) {
          app.globalData.connected = true;
          this.nub_time_d = 1;

          uni.setStorageSync("deviceList", this.deviceList);
          uni.setStorageSync("serviceInfo", this.serviceInfo);

          uni.setStorageSync("writeCharacteristicsInfo", this.writeCharacteristicsInfo);
          //notifyCharacteristicsInfo
          uni.setStorageSync("notifyCharacteristicsInfo", this.notifyCharacteristicsInfo);
          /**/
          uni.setStorageSync("deviceInfo", this.deviceInfo);
          app.globalData.is_yuancheng = 0;
          if (this.lang == 1) {
            uni.showModal({
              title: "Connection successful",
              // content: '您的位置信息将用获取信息',
              success: (res) => {
                uni.navigateBack({
                  //返回上一个页面
                  delta: 1,
                });
              },
            });
          } else {
            uni.showModal({
              title: "连接成功",
              // content: '您的位置信息将用获取信息',
              success: (res) => {
                uni.navigateBack({
                  //返回上一个页面
                  delta: 1,
                });
              },
            });
          }
        }
        // this.funReadPage(value)
        // this.Rec_data_deal(value);
      });

      setTimeout(function () {
        that.handleSearchDevices();
      }, 1000);
    },
    cl_datas() {
      app.globalData.checkpage = 0;
      app.globalData.mare_data = null;
      let cl_data = app.globalData.mare_data;
      console.log(9797, cl_data);
    },
    heartbeat() {
      let that = this;

      //AA 0C 00 10 01 1F 00 00 00 00 00 00 DB 79
      console.log("读秒归0");
      //0xdb, 0x79,
      // 0 - 255
      let h_i = this.h_i;
      if (h_i >= 255) {
        this.h_i = 0;
      } else {
        this.h_i++;
      }

      let temp = this.$util.CRC16Modbus([0xaa, 0x0c, 0x00, 0x10, 0x01, 0x01, parseInt(this.h_i, 16), this.h_f, 0x00, 0x00, 0x00, 0x00]);
      console.log("发送心跳", temp);
      let strArray = new Uint8Array(temp);

      const buffer = strArray.buffer;

      // const buffer = new ArrayBuffer(1)
      // const dataView = new DataView(buffer)
      // dataView.setUint8(0, 0)

      // 向低功耗蓝牙设备特征值中写入二进制数据
      uni.writeBLECharacteristicValue({
        // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        deviceId: this.deviceInfo.deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId: this.serviceInfo.uuid,
        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId: this.writeCharacteristicsInfo.uuid,
        // 这里的value是ArrayBuffer类型
        value: buffer,
        writeType: "writeNoResponse",
        success(res) {
          console.log("发送成功");
          // if(that.lian == 1){
          // 	that.data_che();
          // }
          // uni.hideLoading();

          console.log("writeBLECharacteristicValue success", res.errMsg);
        },
        fail(error) {
          uni.hideLoading();
          console.log("fail");
          console.log(error);

          if (error.errCode) {
            uni.showToast({ title: errorCode[error.errCode], icon: "none" });
          } else if (error.errMsg) {
            uni.showToast({ title: error.errMsg, icon: "none" });
          } else {
            uni.showToast({ title: "fail", icon: "none" });
          }
        },
      });
    },
    duqu11() {},

    // 初始化蓝牙模块
    handleInitBluetooth(callback) {
      console.log("测试");
      var that = this;
      // 初始化蓝牙模块
      uni.openBluetoothAdapter({
        success(result) {
          console.log("success");
          // {errno: 0, errMsg: "openBluetoothAdapter:ok"}
          console.log(result);
          // uni.showToast({ title: '正常' })
          this.isInitBluetooth = true;
          if (callback) {
            callback();
          }
        },
        fail(error) {
          setTimeout(function () {
            console.log(11);
            if (that.lang == 1) {
              uni.showToast({ title: "Bluetooth switch not turned on", icon: "none", mask: false });
            } else {
              uni.showToast({ title: "蓝牙开关未开启", icon: "none", mask: false });
            }

            // uni.closeBluetoothAdapter({
            //   success(res) {
            // 	     console.log('ssucess断开了')

            //   },
            //   fail(error) {
            //     console.log('fail断开了')

            //   },
            //   complete() {
            //     console.log('complete断开了')s
            uni.getBluetoothAdapterState({
              success: function (res) {
                var isDiscov = res.discovering; //是否正在搜索设备
                var isDvailable = res.available; //蓝牙适配器是否可用
                if (isDvailable) {
                  var log = "本机蓝牙适配器状态：可用 \n";
                  console.log(log);
                  if (!isDiscov) {
                    that.startBluetoothDevicesDiscovery();
                  } else {
                    var log = "已在搜索设备 \n";
                    console.log(log);
                  }
                }
              },
            });

            that.handleSearchDevices();
          }, 2000);

          // console.log('fail')
          console.log(error);
          // if (error.errCode) {
          //   uni.showToast({ title: errorCode[error.errCode], icon: 'none' })
          // } else if (error.errMsg) {
          //   uni.showToast({ title: error.errMsg, icon: 'none' })
          // } else {
          //   uni.showToast({ title: 'fail', icon: 'none' })
          // }
        },
      });
    },
    // 开始搜寻附近的蓝牙外围设备。此操作比较耗费系统资源，请在搜索并连接到设备后调用 uni.stopBluetoothDevicesDiscovery 方法停止搜索。
    handleSearchDevices() {
      const startBluetoothDevicesDiscovery = () => {
        uni.startBluetoothDevicesDiscovery({
          // services: ['FEE7'],
          allowDuplicatesKey: true,
          success(res) {
            console.log(res);
          },
          fail(error) {
            console.log("fail");
            console.log(error);
            if (error.errCode) {
              uni.showToast({ title: errorCode[error.errCode], icon: "none" });
            } else if (error.errMsg) {
              uni.showToast({ title: error.errMsg, icon: "none" });
            } else {
              uni.showToast({ title: "fail", icon: "none" });
            }
          },
        });
      };
      if (this.isInitBluetooth) {
        startBluetoothDevicesDiscovery();
      } else {
        this.handleInitBluetooth(startBluetoothDevicesDiscovery);
      }
    },
    // 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时，建议调用该接口停止蓝牙搜索。
    handleStopSearch() {
      uni.stopBluetoothDevicesDiscovery({
        success(res) {
          console.log(res);
        },
        fail(error) {},
      });
    },
    // 关闭蓝牙模块。调用该方法将断开所有已建立的连接并释放系统资源。建议在使用蓝牙流程后，与 uni.openBluetoothAdapter 成对调用。
    handleCloseBluetooth() {
      uni.closeBluetoothAdapter({
        success(res) {
          console.log(res);
        },
        fail(error) {
          console.log("fail");
          console.log(error);
          if (error.errCode) {
            uni.showToast({ title: errorCode[error.errCode], icon: "none" });
          } else if (error.errMsg) {
            uni.showToast({ title: error.errMsg, icon: "none" });
          } else {
            uni.showToast({ title: "fail", icon: "none" });
          }
        },
        complete() {
          console.log("complete");
        },
      });
    },
    // 连接低功耗蓝牙设备
    handleConnectDevice(deviceInfo) {
      app.globalData.checkpage = 0;
      app.globalData.mare_data = null;

      if (app.globalData.cli_lan == 1) {
        return;
      }
      app.globalData.cli_lan = 1;
      setTimeout(function () {
        app.globalData.cli_lan = 0;
      }, 2000);
      console.log(deviceInfo, "开始连接");
      // let platform = uni.getSystemInfoSync().platform;
      // if(platform === 'ios'){

      // this.handleStopSearch()
      let ios_deviceId = 0;
      if (this.is_ios == 1) {
        function ab2hex(buffer) {
          const hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
            return ("00" + bit.toString(16)).slice(-2).toUpperCase();
          });
          return hexArr.join(":").slice(6);
        }

        ios_deviceId = ab2hex(deviceInfo.advertisData);
        uni.setStorage("ios_deviceId", ios_deviceId);
      } // 苹果

      // } else{

      //   // 其他
      //  console.log("其他")
      // }

      if (this.lang == 1) {
        uni.showLoading({ title: "Reading data", mask: false });
        //uni.showToast({ title: '', mask: false,duration:1500,icon:"none" });
      } else {
        uni.showLoading({ title: "连接蓝牙中...", mask: false });
        // uni.showToast({ title: '未找到该设备或该设备已被他人绑定', mask: false,duration:1500,icon:"none"});
      }

      //查看是否可绑定
      let that = this;

      if (that.is_ios == 1) {
        var forms = { dev_id: ios_deviceId };
      } else {
        var forms = { dev_id: deviceInfo.deviceId };
      }
      that.link_cnt(deviceInfo);

      // that.$api.request('/api/user/che_dev', forms, '', function(res){
      // 			if(res.code == 1){
      // 				//该设备是否我能连接 ？
      // 				//deviceInfo.deviceId
      // 				console.log(deviceInfo.deviceId,8888)
      // 				that.link_cnt(deviceInfo);
      // 			}else{
      // 				//、showToast
      // 				if(that.lang == 1){
      // 					uni.showModal({
      // 						title: 'The device was not found or has been bound by someone else',
      // 						cancelText: "cancel", // 取消按钮的文字
      // 						confirmText: "ok", // 确认按钮的文字
      // 						// content: '您的位置信息将用获取信息',
      // 						success: (res) => {
      // 						}
      // 					})
      // 					  //uni.showToast({ title: '', mask: false,duration:1500,icon:"none" });
      // 				}else{
      // 					uni.showModal({
      // 						title: '未找到该设备或该设备已被他人绑定',
      // 						// content: '您的位置信息将用获取信息',
      // 						success: (res) => {
      // 						}
      // 					})
      // 					  // uni.showToast({ title: '未找到该设备或该设备已被他人绑定', mask: false,duration:1500,icon:"none"});
      // 				}
      // 				return;
      // 			}
      // });
    },
    link_cnt(deviceInfo) {
      let that = this;
      // 停止搜寻附近的蓝牙外围设备
      this.handleStopSearch();
      console.log("关闭骚聊");
      //关闭其他连接
      uni.stopBluetoothDevicesDiscovery({
        success(res) {
          console.log(res);
        },
        fail(error) {},
      });

      this.lian = 1;

      console.log("开始普通连接", deviceInfo.deviceId);
      uni.showLoading({
        title: "请求连接中...",
      });

      // 连接低功耗蓝牙设备。
      // 若APP在之前已有搜索过某个蓝牙设备，并成功建立连接，可直接传入之前搜索获取的 deviceId 直接尝试连接该设备，无需进行搜索操作。
      uni.createBLEConnection({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: deviceInfo.deviceId,
        success: (res) => {
          console.log("创建连接成功");

          this.deviceInfo = deviceInfo;
          this.handleGetDeviceService();
          // 设置蓝牙最大传输单元。需在 uni.createBLEConnection调用成功后调用，mtu 设置范围 (22,512)。安卓5.1以上有效。
          uni.setBLEMTU({
            deviceId: this.deviceInfo.deviceId,
            mtu: 28,
            success: function (res) {
              console.log("创建远程连接成功", res);
            },
            fail(error) {
              console.log("创建连接失败", error);
              that.link_cnt1(deviceInfo);
            },
          });
        },
        fail(error) {
          console.log("创建普通连接失败");
          that.link_cnt1(deviceInfo);
        },
        error(error) {
          console.log("错误的返回");
        },
      });
    },
    link_cnt1(deviceInfo) {
      let that = this;
      // 停止搜寻附近的蓝牙外围设备
      this.handleStopSearch();
      console.log("关闭骚聊");
      //关闭其他连接
      uni.stopBluetoothDevicesDiscovery({
        success(res) {
          console.log(res);
        },
        fail(error) {},
      });

      this.lian = 1;

      console.log("开始普通连接", deviceInfo.deviceId);

      // 连接低功耗蓝牙设备。
      // 若APP在之前已有搜索过某个蓝牙设备，并成功建立连接，可直接传入之前搜索获取的 deviceId 直接尝试连接该设备，无需进行搜索操作。
      uni.createBLEConnection({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: deviceInfo.deviceId,
        success: (res) => {
          console.log("创建连接成功");

          this.deviceInfo = deviceInfo;
          this.handleGetDeviceService();
          // 设置蓝牙最大传输单元。需在 uni.createBLEConnection调用成功后调用，mtu 设置范围 (22,512)。安卓5.1以上有效。
          uni.setBLEMTU({
            deviceId: this.deviceInfo.deviceId,
            mtu: 28,
            success: function (res) {
              console.log("创建远程连接成功", res);
            },
            fail(error) {
              console.log("创建连接失败", error);
              that.link_cnt2(deviceInfo);
            },
          });
        },
        fail(error) {
          console.log("创建普通连接失败");
          that.link_cnt2(deviceInfo);
        },
        error(error) {
          console.log("错误的返回");
        },
      });
    },
    link_cnt2(deviceInfo) {
      // 停止搜寻附近的蓝牙外围设备

      // 连接低功耗蓝牙设备。
      // 若APP在之前已有搜索过某个蓝牙设备，并成功建立连接，可直接传入之前搜索获取的 deviceId 直接尝试连接该设备，无需进行搜索操作。
      uni.createBLEConnection({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: deviceInfo.deviceId,
        success: (res) => {
          console.log(res, 777777777);
          this.deviceInfo = deviceInfo;
          this.handleGetDeviceService();
          // 设置蓝牙最大传输单元。需在 uni.createBLEConnection调用成功后调用，mtu 设置范围 (22,512)。安卓5.1以上有效。
          uni.setBLEMTU({
            deviceId: this.deviceInfo.deviceId,
            mtu: 28,
            success: function (res) {
              console.log("success");
            },
            fail(error) {
              console.log("fail");
              console.log(error);
              if (error.errCode) {
                uni.showToast({ title: errorCode[error.errCode], icon: "none" });
              } else if (error.errMsg) {
                uni.showToast({ title: error.errMsg, icon: "none" });
              } else {
                uni.showToast({ title: "fail", icon: "none" });
              }
            },
          });
        },
        fail(error) {
          console.log("fail");
          console.log(error);
          if (error.errCode) {
            uni.showToast({ title: errorCode[error.errCode], icon: "none" });
          } else if (error.errMsg) {
            uni.showToast({ title: error.errMsg, icon: "none" });
          } else {
            uni.showToast({ title: "fail", icon: "none" });
          }
          this.lian = 0;
        },
      });
    },
    // 断开与低功耗蓝牙设备的连接
    handleCloseDevice_clone(deviceInfo) {
      app.globalData.checkpage = 0;
      app.globalData.mare_data = null;

      if (app.globalData.cli_lan == 1) {
        return;
      }

      //是否确认断开连接
      let that = this;
      var _that = this;

      if (this.lang == 1) {
        uni.showModal({
          title: "Are you sure to disconnect",

          // content: 'Data read successfully',
          cancelText: "cancel", // 取消按钮的文字
          confirmText: "ok", // 确认按钮的文字
          // content: '您的位置信息将用获取信息',
          success: (res) => {
            if (res.confirm) {
              that.deviceInfo = uni.getStorageSync("deviceInfo");

              // app.globalData.connected = false;
              uni.setStorageSync("dev_data", null);

              uni.setStorageSync("serviceInfo", null);
              uni.setStorageSync("writeCharacteristicsInfo", null);
              uni.setStorageSync("notifyCharacteristicsInfo", null);
              uni.setStorageSync("deviceInfo", null);

              uni.closeBluetoothAdapter({
                success(res) {
                  console.log(deviceInfo.deviceId, 777);

                  uni.closeBLEConnection({
                    deviceId: deviceInfo.deviceId,
                    success(res) {
                      console.log("断开成功", deviceInfo.deviceId);
                      app.globalData.connected = false;
                      uni.setStorageSync("deviceList", null);
                      that.deviceInfo = {};
                      _that.handleInitBluetooth();
                    },
                    fail(error) {
                      console.log(error, "断开失败");
                    },
                  });
                },
                fail(error) {
                  console.log("fail");
                  console.log(error);
                  uni.closeBLEConnection({
                    deviceId: deviceInfo.deviceId,
                    success(res) {
                      console.log("断开成功", deviceInfo.deviceId);
                      uni.setStorageSync("deviceList", null);
                      app.globalData.connected = false;
                      that.deviceInfo = {};
                      _that.handleInitBluetooth();
                    },
                    fail(error) {},
                  });
                },
                complete() {
                  console.log("complete");
                  app.globalData.connected = false;

                  that.deviceInfo = {};
                  _that.handleInitBluetooth();
                },
              });
            }
          },
        });
      } else {
        uni.showModal({
          title: "是否确认断开连接",
          // content: '您的位置信息将用获取信息',
          success: (res) => {
            if (res.confirm) {
              that.deviceInfo = uni.getStorageSync("deviceInfo");

              // app.globalData.connected = false;
              uni.setStorageSync("dev_data", null);

              uni.setStorageSync("serviceInfo", null);
              uni.setStorageSync("writeCharacteristicsInfo", null);
              uni.setStorageSync("notifyCharacteristicsInfo", null);
              uni.setStorageSync("deviceInfo", null);

              uni.closeBluetoothAdapter({
                success(res) {
                  console.log(deviceInfo.deviceId, 777);

                  uni.closeBLEConnection({
                    deviceId: deviceInfo.deviceId,
                    success(res) {
                      console.log("断开成功", deviceInfo.deviceId);
                      app.globalData.connected = false;
                      uni.setStorageSync("deviceList", null);
                      that.deviceInfo = {};
                      _that.handleInitBluetooth();
                    },
                    fail(error) {
                      console.log(error, "断开失败");
                    },
                  });
                },
                fail(error) {
                  console.log("fail");
                  console.log(error);
                  uni.closeBLEConnection({
                    deviceId: deviceInfo.deviceId,
                    success(res) {
                      console.log("断开成功", deviceInfo.deviceId);
                      uni.setStorageSync("deviceList", null);
                      app.globalData.connected = false;
                      that.deviceInfo = {};
                      _that.handleInitBluetooth();
                    },
                    fail(error) {},
                  });
                },
                complete() {
                  console.log("complete");
                  app.globalData.connected = false;

                  _that.deviceInfo = {};
                  _that.handleInitBluetooth();
                },
              });
            }
          },
        });
      }

      // uni.closeBLEConnection({
      //   deviceId: item.deviceId,
      //   success(res) {
      //     console.log(res)
      //     uni.showToast({ title: '已断开连接' })
      //   },
      //   fail(error) {
      //     console.log('fail')
      //     console.log(error)
      //     if (error.errCode) {
      //       uni.showToast({ title: errorCode[error.errCode], icon: 'none' })
      //     } else if (error.errMsg) {
      //       uni.showToast({ title: error.errMsg, icon: 'none' })
      //     } else {
      //       uni.showToast({ title: 'fail', icon: 'none' })
      //     }
      //   },
      // })
    },
    // 获取蓝牙设备所有服务(service)。
    handleGetDeviceService() {
      // uni.showToast({ title: '设备已连接，读取信息' })

      // if(this.lang == 1){

      // 	uni.showLoading({ title: 'Reading data', mask: false });
      // }else{

      // 	uni.showLoading({ title: '读取数据中', mask: false });
      // }

      console.log("star link dev", this.deviceInfo.deviceId);

      //AA 0C 00 10 01 1F 00 00 00 00 00 00 DB 79
      let that = this;

      uni.getBLEDeviceServices({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: this.deviceInfo.deviceId,
        success: (res) => {
          console.log("device services:", res.services);

          // this.deviceInfo.advertisServiceUUIDs 里只有一项，值是 0000FFE0-0000-1000-8000-00805F9B34FB
          // {uuid: "0000180A-0000-1000-8000-00805F9B34FB", isPrimary: true}
          this.serviceInfo = res.services.find((item) => item.isPrimary && item.uuid === "0000FFE0-0000-1000-8000-00805F9B34FB");
          // this.serviceInfo = res.services.find((item) => item.isPrimary && item.uuid === '0000FFE9-0000-1000-8000-00805F9B34FB')

          //0000FFE0-0000-1000-8000-00805F9B34FB
          // 获取蓝牙设备某个服务中所有特征值(characteristic)。									0000ffe9-0000-1000-8000-00805f9b34fb
          uni.getBLEDeviceCharacteristics({
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
            deviceId: this.deviceInfo.deviceId,
            // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
            serviceId: this.serviceInfo.uuid,
            success: (res) => {
              console.log("特征值", res.characteristics);

              res.characteristics.forEach((item) => {
                if (item.properties.write) {
                  console.log("可写特征值", item);
                  this.writeCharacteristicsInfo = item;
                }

                if (item.properties.indicate || item.properties.notify) {
                  console.log("可订阅特征值", item);
                  this.notifyCharacteristicsInfo = item;

                  // 启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值。注意：必须设备的特征值支持 notify 或者 indicate 才可以成功调用。 另外，必须先启用 notifyBLECharacteristicValueChange 才能监听到设备 characteristicValueChange 事件
                  uni.notifyBLECharacteristicValueChange({
                    state: true, // 启用 notify 功能
                    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                    deviceId: this.deviceInfo.deviceId,
                    // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                    serviceId: this.serviceInfo.uuid,
                    // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
                    // characteristicId: this.notifyCharacteristicsInfo.uuid,
                    characteristicId: item.uuid,
                    success: (res) => {
                      console.log("订阅特征值   开始读取", res.errMsg);

                      setTimeout(() => {
                        that.handleWriteValue_cont();
                      }, 300);

                      // setTimeout(function(){
                      //   that.handleWriteValue_suiji();
                      //   setTimeout(function(){
                      //   		that.handleWriteValue_suiji();
                      // 		setTimeout(function(){
                      // 				that.handleWriteValue_suiji();
                      // 				setTimeout(function(){
                      // 						that.handleWriteValue_suiji();
                      // 						setTimeout(function(){
                      // 								that.handleWriteValue_suiji();
                      // 								setTimeout(function(){
                      // 										that.handleWriteValue();
                      // 								},150);
                      // 						},150);
                      // 				},150);
                      // 		},150);
                      //   },150);
                      // },150);
                    },
                    fail(error) {
                      console.log("fail");
                      console.log(error);
                      if (error.errCode) {
                        uni.showToast({ title: errorCode[error.errCode], icon: "none" });
                      } else if (error.errMsg) {
                        uni.showToast({ title: error.errMsg, icon: "none" });
                      } else {
                        uni.showToast({ title: "fail", icon: "none" });
                      }
                    },
                  });
                }
              });
            },
            fail(error) {
              console.log("fail");
              console.log(error);
              if (error.errCode) {
                uni.showToast({ title: errorCode[error.errCode], icon: "none" });
              } else if (error.errMsg) {
                uni.showToast({ title: error.errMsg, icon: "none" });
              } else {
                uni.showToast({ title: "fail", icon: "none" });
              }
            },
          });
        },
        fail(error) {
          console.log("fail");
          console.log(error);
          if (error.errCode) {
            uni.showToast({ title: errorCode[error.errCode], icon: "none" });
          } else if (error.errMsg) {
            uni.showToast({ title: error.errMsg, icon: "none" });
          } else {
            uni.showToast({ title: "fail", icon: "none" });
          }
        },
      });
    },
    handleWriteValue_suiji() {
      let that = this;
      this.nub_time_d = 0;
      console.log("开始随机 随机后再发送普通数据");
      let strArray = new Uint8Array([
        0xc9, 0x14, 0x02, 0x4c, 0x44, 0x47, 0x45, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d,
      ]);

      function ab2hex(buffer) {
        const hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
          return ("00" + bit.toString(16)).slice(-2);
        });
        return hexArr.join("");
      }

      function random(lower, upper) {
        return Math.floor(Math.random() * (upper - lower + 1)) + lower;
      }

      //写个检测的
      let num_sj = random(1, 255);
      let nun_hex = ("00" + num_sj.toString(16)).slice(-2);

      strArray[10] = "0x" + nun_hex;

      let PlusCode = strArray[10] + 0xea;
      PlusCode = PlusCode ^ 0xdb;
      PlusCode = PlusCode + 0xbf;
      PlusCode = PlusCode ^ 0x5a;
      PlusCode = PlusCode + 0xdb;
      PlusCode = PlusCode ^ 0xbd;
      PlusCode = PlusCode & 0x7f;
      strArray[11] = PlusCode;
      console.log(1111, strArray[10], strArray[11]);

      let temp = strArray[0];
      for (let i = 1; i < strArray.length - 2; i++) {
        temp ^= strArray[i];
      }
      strArray[strArray.length - 2] = temp;
      const buffer = strArray.buffer;

      // const buffer = new ArrayBuffer(1)
      // const dataView = new DataView(buffer)
      // dataView.setUint8(0, 0)

      //随机数？

      /*
	 PlusCode= (uchar) (Byte7+0xEA) :
	 PlusCode=(uchar) (PlusCode 0xDB) :
	 PlusCode=(uchar)(PlusCode+0xBF) ;-(uchar) (PlusCode0x5A) :PlusCode=PlusCode=(uchar) (PlusCode+0xDB) ;PlusCode= (uchar) (PlusCode 0xBD)PlusCode=PlusCode&0x7F;+
	  **/

      // 向低功耗蓝牙设备特征值中写入二进制数据
      uni.writeBLECharacteristicValue({
        // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        deviceId: this.deviceInfo.deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId: this.serviceInfo.uuid,
        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId: this.writeCharacteristicsInfo.uuid,
        // 这里的value是ArrayBuffer类型
        value: buffer,
        writeType: "writeNoResponse",
        success(res) {
          console.log("读秒开始");
          // if(that.lian == 1){
          // 	that.data_che();
          // }

          console.log("writeBLECharacteristicValue success", res.errMsg);
        },
        fail(error) {
          console.log("fail");
          console.log(error);

          if (error.errCode) {
            uni.showToast({ title: errorCode[error.errCode], icon: "none" });
          } else if (error.errMsg) {
            uni.showToast({ title: error.errMsg, icon: "none" });
          } else {
            uni.showToast({ title: "fail", icon: "none" });
          }
        },
      });
    },

    // 向低功耗蓝牙设备特征值中写入二进制数据
    handleWriteValue() {
      let that = this;
      this.nub_time_d = 0;
      console.log("读秒归0");
      let strArray = new Uint8Array([
        0xc9, 0x14, 0x02, 0x4c, 0x44, 0x47, 0x45, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d,
      ]);
      let temp = strArray[0];
      for (let i = 1; i < strArray.length - 2; i++) {
        temp ^= strArray[i];
      }
      strArray[strArray.length - 2] = temp;
      const buffer = strArray.buffer;

      // const buffer = new ArrayBuffer(1)
      // const dataView = new DataView(buffer)
      // dataView.setUint8(0, 0)

      // 向低功耗蓝牙设备特征值中写入二进制数据
      uni.writeBLECharacteristicValue({
        // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        deviceId: this.deviceInfo.deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId: this.serviceInfo.uuid,
        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId: this.writeCharacteristicsInfo.uuid,
        // 这里的value是ArrayBuffer类型
        value: buffer,
        writeType: "writeNoResponse",
        success(res) {
          console.log("读秒开始");
          if (that.lian == 1) {
            that.data_che();
          }

          console.log("writeBLECharacteristicValue success", res.errMsg);
        },
        fail(error) {
          console.log("fail");
          console.log(error);

          if (error.errCode) {
            uni.showToast({ title: errorCode[error.errCode], icon: "none" });
          } else if (error.errMsg) {
            uni.showToast({ title: error.errMsg, icon: "none" });
          } else {
            uni.showToast({ title: "fail", icon: "none" });
          }
        },
      });
    },
    handleWriteValue_cont() {
      let that = this;

      //AA 0C 00 10 01 1F 00 00 00 00 00 00 DB 79
      console.log("读秒归0111");
      //0xdb, 0x79,

      let temp = this.$util.CRC16Modbus([0xaa, 0x0c, 0x00, 0x10, 0x01, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);

      let strArray = new Uint8Array(temp);

      const buffer = strArray.buffer;

      // const buffer = new ArrayBuffer(1)
      // const dataView = new DataView(buffer)
      // dataView.setUint8(0, 0)

      // 向低功耗蓝牙设备特征值中写入二进制数据
      uni.writeBLECharacteristicValue({
        // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        deviceId: this.deviceInfo.deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId: this.serviceInfo.uuid,
        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId: this.writeCharacteristicsInfo.uuid,
        // 这里的value是ArrayBuffer类型
        value: buffer,
        writeType: "writeNoResponse",
        success(res) {
          console.log("发送成功9712");
          if (that.lian == 1) {
            that.data_che();
          }
          // uni.hideLoading();

          console.log("writeBLECharacteristicValue success", res.errMsg);
        },
        fail(error) {
          uni.hideLoading();
          console.log("fail");
          console.log(error);

          if (error.errCode) {
            uni.showToast({ title: errorCode[error.errCode], icon: "none" });
          } else if (error.errMsg) {
            uni.showToast({ title: error.errMsg, icon: "none" });
          } else {
            uni.showToast({ title: "fail", icon: "none" });
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.list-container {
  padding: 30rpx;
  .list-item {
    padding: 20rpx;
    outline: 2rpx dashed #ccc;
  }
}
</style>

<style lang="scss" scoped>
.lanya {
  background: #111823;
  min-height: 100vh;
  float: left;
  width: 100%;

  .lists {
    margin-top: 10px;
    width: 100%;
    background: #293241;
    height: 120px;
    line-height: 60px;
    box-shadow: 0 0 10rpx 0 rgba(118, 156, 255, 0.3);
    float: left;
    .list {
      width: 100%;
      color: #7a818e;
      float: left;
      font-size: 30rpx;

      &:last-child {
        border-bottom: none;
      }
      .fa {
        font-weight: 500;
        margin-left: 25rpx;
        float: left;
        color: #fff;
      }
      .icon {
        margin-right: 16rpx;
        width: 128rpx;
        height: 128rpx;
        float: left;
        margin-left: 10px;
      }
      .rightimg_str {
        width: 80px;
        color: #fff;
        float: right;
        height: 30px;
        line-height: 30px;
        font-size: 12px;
        background: #44b31d;
        border-radius: 5em;
        margin-right: 5px;
        text-align: center;
        margin-top: 15px;
      }
    }
  }

  .list {
    height: 500rpx;
    overflow-y: scroll;
    background: #fff;
    border-radius: 10rpx;
    margin: 20rpx;
    margin-top: 155rpx;
    .list-one {
      padding: 0 28rpx;
      border-bottom: 1px solid #e6e6e6;
      height: 105rpx;
      line-height: 105rpx;
      font-size: 30rpx;
      color: #333333;
    }
    .list-one:last-child {
      border: none;
    }
    .list-one:active {
      background: #cccccc;
    }
  }
}
</style>
